package web.servlet.cookiesession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author Administrator
 * @Date 2020/6/2 16:15
 **/
@WebServlet("/visitTime")
public class VisitTime extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /** 获取cookie(数组)
         * 遍历数组
         * 判断cookie的key是不是"lastTime"
         */
        resp.setContentType("text/html;charset=utf-8");
        Cookie[] cookies = req.getCookies();
        boolean flag = false;
        if (cookies != null && cookies.length > 0) {
            for (int i = 0; i < cookies.length; i++) {
                String name = cookies[i].getName();
                if (name.equals("lastTime")) {
                    /**不是第一次访问*/
                    resp.getWriter().write("欢迎回来，上次访问时间是：" +URLDecoder.decode(cookies[i].getValue(),"utf-8"));
                    /**时间有特殊字符*/
                    Date date=new Date();
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String s1 = sdf.format(date);
                    String s = URLEncoder.encode(s1, "utf-8");
                    cookies[i].setValue(s);
                    cookies[i].setMaxAge(24 * 60 * 60);
                    resp.addCookie(cookies[i]);
                    flag = true;
                    break;
                }
            }
        }
        if(cookies==null||cookies.length==0||!flag){
            resp.getWriter().write("欢迎首次访问");
            Date date=new Date();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String d = sdf.format(date);
            /**日期时间有特殊字符：对特殊字符处理*/
            String s = URLEncoder.encode(d, "utf-8");
            Cookie cookie=new Cookie("lastTime",s);
            cookie.setMaxAge(60*60*60);
            resp.addCookie(cookie);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
